package com.tairanchina.joat;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 插件管理器
 * Created by 周靖捷 on 2016/10/17.
 */
public class GenericPluginManager implements PluginManager {
    ConcurrentHashMap<PluginInstaller, Plugin> pluginInstanceMap = new ConcurrentHashMap<PluginInstaller, Plugin>();

    public void install(PluginInstaller installer) {
        Plugin plugin = installer.install(this);
        pluginInstanceMap.putIfAbsent(installer, plugin);
    }

    public void update(PluginInstaller installer) {
        if (pluginInstanceMap.contains(installer)) {
            Plugin plugin = installer.update(this);
            pluginInstanceMap.put(installer, plugin);
        }
    }

    public void uninstall(PluginInstaller installer) {
        if (pluginInstanceMap.contains(installer)) {
            installer.uninstall(this);
            pluginInstanceMap.remove(installer);
        }
    }

    public List<PluginInstaller> list() {
        return new ArrayList<PluginInstaller>(pluginInstanceMap.keySet());
    }

    public Optional<PluginInstaller> findPluginInstaller(String installerId) {
        for (PluginInstaller installer : pluginInstanceMap.keySet()) {
            if (installer.getPluginMeta().getPluginId().equals(installerId)) {
                return Optional.of(installer);
            }
        }
        return Optional.empty();
    }

    public Plugin instance(String installerId) {
        for (PluginInstaller installer : pluginInstanceMap.keySet()) {
            if (installer.getPluginMeta().getPluginId().equals(installerId)) {
                return pluginInstanceMap.get(installer);
            }
        }
        return null;
    }
}
